package com.hz.house.service;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.hz.house.bean.entity.AnswerReplyBean;
import com.hz.house.bean.entity.FAQAnswerBean;
import com.hz.house.bean.entity.FAQBean;
import com.hz.house.bean.entity.FAQTypeRef;
import com.hz.house.bean.entity.OfficialAccountbean;
import com.hz.house.bean.vo.AnswerQuestionInfo;
import com.hz.house.bean.vo.AnswerReplyInfo;
import com.hz.house.bean.vo.FAQBillInfo;
import com.hz.house.bean.vo.FAQInfo;
import com.hz.house.bean.vo.FAQSearch;
import com.hz.house.bean.vo.MyAnswerVo;
import com.hz.house.bean.vo.SimpleBean;
import com.hz.house.common.Constants;
import com.hz.house.common.ResultUtil;
import com.hz.house.common.ThreadPool;
import com.hz.house.dao.FAQMapper;
import com.hz.house.enums.FQATypeEnums;

import lombok.extern.slf4j.Slf4j;

/**
 * 买房问答业务层
 * @author lfw
 *
 */
@Service("buyHouseFAQService")
@Slf4j
public class BuyHouseFAQService {

	@Autowired
	private FAQMapper fAQMapper;
	
	@Autowired
	private BbsCacheService bbsCacheService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private ThreadPool threadPool;
	
	@Resource
	private RestTemplate ribbonTemplate;
	
	@Resource
	private RestTemplate restTemplate;
	
	//默认的用户头像
	private String defaultHeadImg= "https://housessmall-dev-index-img-1258778894."
				+ "cos.ap-chengdu.myqcloud.com/sellman/headImg_xiong.png";
	private String faqBillBackgroundImg = "https://housessmall-dev-index-img-1258778894."
			+ "cos.ap-chengdu.myqcloud.com/community/icon_wdTiwen.png";
	
	private Map<Integer,Integer> lookNum = new ConcurrentHashMap<>();
	
	
	private void addFaqLookNum(List<FAQBean> faqs) {
		faqs.forEach(f->{
			addLookNum(f.getId());
		});
	}
	
	private void addLookNum(int faqId) {
		Integer num = lookNum.get(faqId);
		if(num==null) 
			lookNum.put(faqId, getRadomInt(5, 15));
		else
			lookNum.put(faqId, num+getRadomInt(5, 15));
	}
	
	private int getRadomInt(int min,int max) {
		int x = new Random().nextInt(max-min)+min;
		return x;
	}
	
	
	/**
	 * <p>前期先这样吧  后面再走es或走缓存
	 * @param faq
	 * @param customerId
	 * @return
	 */
	@Transactional
	public Object askQuestionFaq(FAQInfo faq,int customerId) {
		
		if(StringUtils.isEmpty(faq.getQuestion()))
			return ResultUtil.fail("提问失败");
		if(StringUtils.isEmpty(faq.getType()))
			faq.setType("10");
		//入库
		FAQBean b = new FAQBean();
		b.setId(bbsCacheService.getFaqId());
		b.setCreateTime(new Date());
		b.setCustomerId(customerId);
		b.setQuestion(faq.getQuestion());
		int x = this.fAQMapper.addNewQuestion(b);
		if(x>0) {
			//插入类型
			List<FAQTypeRef> tps = new ArrayList<>();
			String[] ts = faq.getType().split(",");
			for(String t:ts)
				tps.add(new FAQTypeRef(b.getId(),Integer.parseInt(t)));
			this.fAQMapper.addFaqTypes(tps);
			return ResultUtil.ok(b.getId());
		}
		return ResultUtil.fail("提问失败");
	}
	
	/**
	 * 获取问他列表数据
	 * @param page
	 * @return
	 */
	public Object getFaqList(FAQSearch s) {
		if(s.getPage()==null||s.getPage()<1)
			s.setPage(1);
		long st = System.currentTimeMillis();
		//是否是走检索
		boolean isSearch = (!StringUtils.isEmpty(s.getTypes())||s.getOrder()!=null
				||s.getIsAnwsered()!=null || !StringUtils.isEmpty(s.getKeyword()));
		System.out.println("isSearch:"+isSearch);
		Map<String,Object> m = new HashMap<>();
		m.put("page", (s.getPage()-1)*10);
		m.put("size", 10);
		
		if(!isSearch) {
			//走缓存
			List<FAQBean> rows = this.bbsCacheService.getFaqListPage(s.getPage());
			if(rows!=null) {
				m.put("rows", rows);
				m.put("total",this.bbsCacheService.getFaqListPageTotal());
			}
		}
		//处理查询条件
		//处理类型查询
		if(!StringUtils.isEmpty(s.getTypes())) {
			String[] tids = s.getTypes().split(",");
			List<Integer> ts = new ArrayList<>();
			for(String tid:tids)
				ts.add(Integer.parseInt(tid));
			m.put("typeIds", ts);
		}
		//处理回答状态查询
		if(s.getIsAnwsered()!=null) {
			//0，1，2 如果是2则全部，不做处理
			if(s.getIsAnwsered()<2)
				m.put("isAnswered",s.getIsAnwsered());
		}
		//处理排序
		if(s.getOrder()!=null) {
			if(s.getOrder()==1)
				m.put("order","lookNum");
			else if(s.getOrder()==2)
				m.put("order", "createTime");
		}
		//处理模糊查询
		if(!StringUtils.isEmpty(s.getKeyword())) 
			m.put("keyword", s.getKeyword());
		
		List<FAQBean> faqs = this.fAQMapper.getFaqList(m);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		faqs.forEach(q->{
			q.setTime(sdf.format(q.getCreateTime()));
			q.setCreateTime(null);
			if(StringUtils.isEmpty(q.getHeadImg()))
				q.setHeadImg(defaultHeadImg);
			if(StringUtils.isEmpty(q.getUserName()))
				q.setUserName("用户"+(String.valueOf(q.getCustomerId()).substring(2)));
		});
		Integer total = this.fAQMapper.getFaqListTotal(m);
		m.clear();
		m.put("rows", faqs);
		m.put("total", total==null?0:total);
		if(faqs.size()>0) {
			//查询类型
			List<FAQTypeRef> refs = this.fAQMapper.getTypes(faqs);
			formatTypes(refs, faqs);
		}
		if(!isSearch) {
			//缓存数据
			Integer totalx = this.bbsCacheService.getFaqListPageTotal();
			if(totalx==null)
				this.bbsCacheService.setFaqListPageTotalCache(total==null?0:total);
			this.bbsCacheService.setFaqListPageCache(faqs, s.getPage());
		}
		//加入浏览量
		addFaqLookNum(faqs);
		long ed = System.currentTimeMillis();
		log.info("拉取买房问答列表耗时:"+(ed-st)+"ms!");
		return ResultUtil.ok(m);
	}
	
	//FQATypeEnums
	private void formatTypes(List<FAQTypeRef> refs ,List<FAQBean> faqs) {
		for(FAQBean faq:faqs) {
			List<String> ts = faq.getTypes();
			if(ts==null)
				faq.setTypes(ts = new ArrayList<>());
			for(FAQTypeRef r:refs) {
				if(r.getFaqId()==faq.getId())
					ts.add(FQATypeEnums.getTypeNameById(r.getTypeId()));
			}
		}
	}
	
	public Object answerQuestion(AnswerQuestionInfo aqi,int customerId){
		if(aqi.getFaqId()==null ||aqi.getFaqId()<1)
			return ResultUtil.fail("回答失败");
		if(StringUtils.isEmpty(aqi.getContent()))
			return ResultUtil.fail("回答失败");
		if(!this.commonService.checkContent(aqi.getContent()))
			return ResultUtil.fail("容包含敏感词汇");
		FAQAnswerBean answer = new FAQAnswerBean();
		answer.setContent(aqi.getContent());
		answer.setCreateTime(new Date());
		answer.setCustomerId(customerId);
		answer.setFaqId(aqi.getFaqId());
		//检查是否是官方的用户评论的
		int isOfficial = this.commonService.isUserOfficialAccount(customerId)?1:0;
		answer.setIsOfficial(isOfficial);
		int x = this.fAQMapper.addAnswer(answer);
		if(x>0) {
			afterAnserQ(aqi.getFaqId());
			return ResultUtil.ok();
		}
		return ResultUtil.fail("回答失败");
	}
	
	
	private void afterAnserQ(int faqId) {
		//推送有新的回答消息给提问用户
		
		this.threadPool.runInThreadPool(()->{
			Integer cid = this.fAQMapper.getFaqCustomerId(faqId);
			if(cid==null)
				return;
			Map<String,Object> m = new HashMap<>();
			m.put("toCustomerId", cid);
			m.put("faqId", faqId);
			m.put("title", "提问回复提醒");
			m.put("content", "您的提问有新的回复了,赶快去看看吧!");
			String data = JSON.toJSONString(m);
			String url = "http://house-small-sellman/ms/customer/sendFaqAMsg";
			String res = this.doPostSendMsg(data, url);
			System.out.println("发送回答问题提醒结果:"+res);
		});
	}
	
	/**封装http请求发送post,返回接口的结果 */
	private String doPostSendMsg(String data,String url) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> entity = new HttpEntity<String>(data, headers);
		String json = this.ribbonTemplate.postForObject(url, entity, String.class);
		return json;
	}
	
 
	public Object praiseAnswer(Integer answerId,int customerId,Integer iHasPraise) {
		if(answerId==null)
			return ResultUtil.fail("点赞失败");
		if(iHasPraise==null)
			iHasPraise=0;
		if(iHasPraise==0) {
			//执行点赞
			try {
				this.fAQMapper.praiseA(customerId, answerId);
				return ResultUtil.ok();
			} catch (Exception e) {
				if(e instanceof DuplicateKeyException)
					return ResultUtil.fail("已经点过赞了");
				e.printStackTrace();
				return ResultUtil.fail("点赞失败");
			}
		}
		//取消点赞
		this.fAQMapper.delPraiseA(customerId, answerId);
		return ResultUtil.ok();
	}
	
	
	public Object replyAnswer(AnswerReplyInfo reply,int customerId) {
		if(reply.getAnswerId()==null)
			return ResultUtil.fail("回复失败");
		if(StringUtils.isEmpty(reply.getContent()))
			return ResultUtil.fail("回复失败");
		if(reply.getFaqId()==null)
			return ResultUtil.fail("回复失败");
		//内容安全检查
		if(!this.commonService.checkContent(reply.getContent()))
			return ResultUtil.fail("内容包含敏感词汇");
		AnswerReplyBean r = new AnswerReplyBean();
		r.setAnswerId(reply.getAnswerId());
		r.setBeReplyedId(reply.getReplyId()==null?0:reply.getReplyId());
		r.setContent(reply.getContent());
		r.setCreateTime(new Date());
		r.setCustomerId(customerId);
		r.setFaqId(reply.getFaqId());
		int isOfficial = this.commonService.isUserOfficialAccount(customerId)?1:0;
		r.setIsOfficial(isOfficial);
		//入库
		this.fAQMapper.addReply(r);
		return ResultUtil.ok();
	}
	
	public Object getFaqDetail(Integer faqId,int customerId) {
		
		if(faqId==null||faqId<1)
			return ResultUtil.fail("查询失败");

		FAQBean q = this.fAQMapper.getFAQDetail(faqId);
		List<FAQBean> faqs = new ArrayList<>();
		faqs.add(q);
		List<FAQTypeRef> refs = this.fAQMapper.getTypes(faqs);
		formatTypes(refs, faqs);
		//格式化时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		q.setTime(sdf.format(q.getCreateTime()));
		q.setCreateTime(null);
		q.setMyself(customerId==q.getCustomerId());
		if(StringUtils.isEmpty(q.getHeadImg()))
			q.setHeadImg(defaultHeadImg);
		if(StringUtils.isEmpty(q.getUserName()))
			q.setUserName("用户"+(String.valueOf(q.getCustomerId()).substring(2)));
		//添加浏览量
		addLookNum(faqId);
		return ResultUtil.ok(q);
	}

	public Object zhuiWen(String content,Integer faqId) {
		if(StringUtils.isEmpty(content))
			return ResultUtil.fail("追问失败");
		if(faqId==null|| faqId<1)
			return  ResultUtil.fail("追问失败");
		if(!this.commonService.checkContent(content))
			return ResultUtil.fail("包含敏感词汇");
		int x = this.fAQMapper.zhuiWen(content, faqId);
		if(x>0)
			return ResultUtil.ok();
		return ResultUtil.ok("已经追问过了");
	}
	
	
	public Object getAswersAndReplysList(Integer page,int customerId,Integer faqId) {
		if(page==null||page<1)
			page=1;
		long st = System.currentTimeMillis();
		//查询回答
		Integer total = this.fAQMapper.getAnswerListTotal(faqId);
		Map<String,Object> m = new HashMap<>();
		if(total==null||total==0) {
			m.put("total",0);
			m.put("rows", null);
			return ResultUtil.ok(m);
		}
 		List<FAQAnswerBean> as = this.fAQMapper.getAnswerList((page-1)*10, 10,faqId);
 		//格式化时间
 		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
		as.forEach(a->{
			a.setTime(sdf.format(a.getCreateTime()));
			a.setCreateTime(null);
		});
		//查询本页的回答的回复内容
		List<AnswerReplyBean> rs = this.fAQMapper.getAnswerReplys(as);
		//格式化回复和评论
		formatReplyAndAnswer(as, rs);
		//处理我是否点赞了
		List<Integer> ips = this.fAQMapper.getIPraise(customerId);
		if(ips.size()>0) {
			for(Integer aid:ips) {
				for(FAQAnswerBean a:as) {
					if(aid.intValue()==a.getId()) {
						a.setIHasPraise(true);
						break;
					}
				}
			}
		}
		m.put("rows", as);
		m.put("total", total);
		long ed = System.currentTimeMillis();
		log.info("拉取买房问答回答列表耗时："+(ed-st)+"ms!");
		return ResultUtil.ok(m);
	}
	
	private void formatReplyAndAnswer(List<FAQAnswerBean> as,List<AnswerReplyBean> rs) {
		
		List<OfficialAccountbean> officials = this.bbsCacheService.getOfficialAccount();
		
		for(FAQAnswerBean a:as) {
			if(a.getReplys()==null)
				a.setReplys(new ArrayList<>());
			//处理置业顾问
			a.setSellMan(!StringUtils.isEmpty(a.getSellManName()));
			if(a.isSellMan()) {
				a.setUserName("置业顾问"+a.getSellManName());
				a.setSellManName(null);
			}
			//处理官方回复
			if(a.getIsOfficial()==1) {
				OfficialAccountbean o = this.getOfficial(officials, a.getCustomerId());
				if(o!=null) {
					a.setUserName(o.getOffcialAccountName());
					a.setSellMan(false);
					a.setHeadImg(Constants.OFFCIAL_USER_HEADIMG);
				}else
					a.setIsOfficial(0);
			}
			for(AnswerReplyBean r:rs) {
				if(r.getAnswerId()!=a.getId())
					continue;
				a.getReplys().add(r);
				//处理置业顾问
				r.setSellMan(!StringUtils.isEmpty(r.getSellManName()));
				if(r.isSellMan()) {
					r.setUserName("置业顾问"+r.getSellManName());
					r.setSellManName(null);
				}
				//处理官方回复
				if(r.getIsOfficial()==1) {
					OfficialAccountbean o = this.getOfficial(officials, r.getCustomerId());
					if(o!=null) {
						r.setUserName(o.getOffcialAccountName());
						r.setSellMan(false);
					}else
						r.setIsOfficial(0);
				}
				//处理被回复者
				if(r.getBeReplyedId()>0)
					handleBeReplyName(r, rs,officials);
				r.setReplyerName(r.getUserName());
			}
		}
	}
	
	private OfficialAccountbean getOfficial(List<OfficialAccountbean> acs,int customerId) {
		if(acs==null||acs.size()==0)
			return null;
		for(OfficialAccountbean o:acs) {
			if(o.getCustomerId().intValue()==customerId)
				return o;
		}
		
		return null;
	}
	
	private void handleBeReplyName(AnswerReplyBean r,List<AnswerReplyBean> rs,List<OfficialAccountbean> officials) {
		for(AnswerReplyBean ar:rs) {
			if(ar.getId()==r.getBeReplyedId()) {
				if(ar.getIsOfficial()==1) {
					OfficialAccountbean o = this.getOfficial(officials, r.getCustomerId());
					if(o!=null) 
						r.setBeRelyedName(o.getOffcialAccountName());
					else {
						r.setIsOfficial(0);
						r.setBeRelyedName(ar.getUserName());
					}
					break;	
				}
				r.setBeRelyedName(ar.getUserName());
			}
		}
	}
	
	
	
	public void synFaqLookNums() {
		log.info("本次需要同步浏览量的条为:"+lookNum.size());
		List<SimpleBean> nums = new ArrayList<>();
		synchronized (lookNum) {
			if(lookNum.size()==0) 
				return;
			lookNum.forEach((k,v)->{
				SimpleBean s = new SimpleBean();
				s.setId(k);
				s.setNum(v);
				nums.add(s);
			});
			lookNum.clear();
		}
		//执行批量更新
		long st =System.currentTimeMillis();
		try {
			this.fAQMapper.synFaqLookNum(nums);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("批量同步问答浏览量异常",e);
		}
		long ed = System.currentTimeMillis();
		log.info("本次批量同步问答浏览量耗时:"+(ed-st)+"ms!");
	}
	
	
	public Object getMyQestion(Integer page,int customerId) {
		if(page==null||page<1)
			page=1;
		Map<String,Object> m = new HashMap<>();
		m.put("page", (page-1)*10);
		m.put("size", 10);
		m.put("customerId", customerId);
		Integer total = this.fAQMapper.getMyFaqListTotal(m);
		if(total==null||total==0) {
			m.clear();
			m.put("rows", null);
			m.put("total", 0);
			return ResultUtil.ok(m);
		}
		List<FAQBean> x = this.fAQMapper.getMyFaqList(m);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		x.forEach(q->{
			q.setTime(sdf.format(q.getCreateTime()));
			q.setCreateTime(null);
		});
		//处理标签
		if(x.size()>0) {
			//查询类型
			List<FAQTypeRef> refs = this.fAQMapper.getTypes(x);
			formatTypes(refs, x);
		}
		m.clear();
		m.put("rows", x);
		m.put("total",total);
		return ResultUtil.ok(m);
	}
	
	
	public Object getMyAnswers(Integer page,int customerId) {
		if(page==null||page<1)
			page=1;
		Map<String,Object> m = new HashMap<>();
		m.put("page", (page-1)*10);
		m.put("size", 10);
		m.put("customerId", customerId);
		Integer total = this.fAQMapper.getMyAnswersTotal(m);
		if(total==null||total==0) {
			m.clear();
			m.put("rows", null);
			m.put("total", 0);
			return ResultUtil.ok(m);
		}
		List<MyAnswerVo> as = this.fAQMapper.getMyAnswers(m);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		as.forEach(a->{
			a.setATime(sdf.format(a.getACreateTime()));
			a.setQTime(sdf.format(a.getQCreateTime()));
			a.setACreateTime(null);
			a.setQCreateTime(null);
		});
		m.clear();
		m.put("rows", as);
		m.put("total",total);
		return ResultUtil.ok(m);
	}

	
	public Object generateFAQBill(Integer faqId){
		if(faqId==null)
			return ResultUtil.fail("生成海报失败");
		//查询用户的头像 问题 
		FAQBillInfo info = this.fAQMapper.getFaqBillInfo(faqId);
		if(info==null)
			return ResultUtil.fail("生成海报失败");
		if(StringUtils.isEmpty(info.getHeadImg()))
			info.setHeadImg(defaultHeadImg);
		//获取小程序二维码
		//获取今日热问二维码  先用死的
		byte[] qrCode=null;
		try {
			qrCode = getFAQQRCode(faqId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取买房问答海报的二维码失败",e);
			return ResultUtil.fail("获取海报失败");
		}
		if(qrCode==null || qrCode.length==0) {
			log.error("获取买房问答海报的二维码失败");
			return ResultUtil.fail("获取海报失败");
		}
//		FileInputStream fis= null;
//		try {
//			fis = new FileInputStream(new File("D:\\text\\qr.png"));
//		} catch (Exception e1) {
//		}
//		byte[] qrCode=null;
//		try {
//			qrCode = new byte[fis.available()];
//			fis.read(qrCode);
//		} catch (Exception e1) {
//		}finally {
//			try {
//				fis.close();
//			} catch (IOException e) {
//			}
//		}
		//开始绘制
		try {
			String base64=drawBill(info, qrCode);
			return ResultUtil.ok(null, base64);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.fail("获取海报失败");
		}
	}
	
	public String drawBill(FAQBillInfo info,byte[] qrCode) throws Exception{
		
		//750，1334
		int x = 600;
		int y = 900;
		//创建底板画布
		BufferedImage billImgBuffer = new BufferedImage(x,y, BufferedImage.TYPE_INT_RGB);// RGB形式
		Graphics2D bill2d = billImgBuffer.createGraphics();
		bill2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//抗锯齿
		bill2d.setBackground(Color.WHITE);//设置背景为白色
		bill2d.clearRect(0, 0, 600, 900);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形
		
		//绘制背景板
		drawBackGround(bill2d);
		//绘制问题内容
		drawQuestion(bill2d, info);
		//绘制用户头像
		drawUserHead(bill2d, info);
		//绘制此问答二维码
		drawFaqQRCode(bill2d, qrCode);
		bill2d.dispose();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(billImgBuffer, "png", bos);
		return Base64.getEncoder().encodeToString(bos.toByteArray());
	}
	
	private void drawBackGround(Graphics2D bill2d) throws Exception {
		bill2d.drawImage(ImageIO.read(new URL(faqBillBackgroundImg)),0,0,600,900,null);
	}
	
	private void drawQuestion(Graphics2D bill2d,FAQBillInfo info) {
		String q = info.getQuestion();
		List<String> qs =  splitQuestion(q);
		Color c = new Color(130,130,130);
		bill2d.setPaint(c);// 设置画笔,设置Paint属性
		Font font = new Font("黑体",Font.PLAIN,24);//平方加粗24字号
		bill2d.setFont(font);//设置画笔
		//行高40
		for(int i=0;i<qs.size();i++) {
			if(qs.size()>3 && i==2) {
				String endLine = qs.get(i);
				String x = endLine.substring(0,endLine.length()-2)+"...";
				bill2d.drawString(x,83,266+(i*40));
				return;
			}
			bill2d.drawString(qs.get(i),83,266+(i*40));
		} 
	}
	
	
	private List<String> splitQuestion(String q){
		List<String> text = new ArrayList<>();
		char[] cs = q.toCharArray();
		StringBuilder sb = new StringBuilder();
		float wordsCount = 0f;
		float nextCount = 0f;
		//每行18个中文字符
		for(int i=0;i<cs.length;i++) {
			sb.append(cs[i]);
			wordsCount = wordsCount+(isEnglish(cs[i])?0.5f:1f);
			nextCount = i==cs.length-1?wordsCount:nextCount+(isEnglish(cs[i+1])?0.5f:1f);
			if(nextCount>=18 || i==cs.length-1) {
				text.add(sb.toString());
				sb = new StringBuilder();
				wordsCount=0f;
				nextCount=0f;
			}
		}
		return text;
	}
	
	private boolean isEnglish(char c) {
		if(c>0 &&c <=127)
			return true;
		return false;
	}
	
	
	private void drawUserHead(Graphics2D bill2d,FAQBillInfo info) throws MalformedURLException, IOException {
		int width=80;
		BufferedImage head = new BufferedImage(80,80, BufferedImage.TYPE_INT_ARGB);// RGB形式
		Graphics2D head2d = head.createGraphics();
		head2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//抗锯齿
		Ellipse2D.Double shape = new Ellipse2D.Double(0,0,79,79);
		head2d.setClip(shape);
		head2d.setColor(Color.WHITE);//设置背景为白色
		head2d.setBackground(Color.WHITE);//设置背景为白色
		BufferedImage bufImg = ImageIO.read(new URL(info.getHeadImg()));
		head2d.drawImage(bufImg.getScaledInstance(640,640,
				Image.SCALE_SMOOTH),0,0,80,80, null);
		head2d.dispose();
		//____________
		head2d = head.createGraphics();
		head2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
        //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
        Stroke s = new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        head2d.setStroke(s);
        head2d.setColor(Color.WHITE);
        head2d.drawOval(0, 0, width - 1 * 2, width - 1 * 2);
        head2d.dispose();
        bill2d.drawImage(head, 260,420,80, 80, null);
	}
	private void drawFaqQRCode(Graphics2D bill2d,byte[] qrCode) throws IOException {
		BufferedImage qrImage = new BufferedImage(144,144, BufferedImage.TYPE_INT_ARGB);// RGB形式
		Graphics2D qr2d = qrImage.createGraphics();
		qr2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//抗锯齿
		BufferedImage qrcode = ImageIO.read(new ByteArrayInputStream(qrCode));
		qr2d.drawImage(qrcode,0,0, 144, 144,null);
		qr2d.dispose();
		bill2d.drawImage(qrImage,230, 650, 144, 144, null);
	}
	
	
	
	private byte[] getFAQQRCode(int faqId) throws Exception{
		String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit"
				+ "?access_token="+this.commonService.getXiaoChengxuToken();
		Map<String,String> m = new HashMap<>();
    	m.put("page", "pages/community/questionDetail/main");
    	m.put("scene",faqId+"");
    	HttpHeaders headers = new HttpHeaders();
	    //设置请求媒体数据类型
	    headers.setContentType(MediaType.APPLICATION_JSON);
	    String json = JSON.toJSONString(m);
	    HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
	    ResponseEntity<byte[]> res = restTemplate.postForEntity(url,formEntity, byte[].class);
	    byte[] x = res.getBody();
		return x;
	}
	
}
